<template>
  <div class="params">
    <el-breadcrumb separator="/" style="margin-bottom: 20px;">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>参数管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card" style="line-height: 0; text-align: left;">
      <div class="title ">
        <p class="el-icon-warning"></p>
        注意:只允许为第三级设置参数
      </div>
      <el-cascader v-model="selectedCategoryPath" :options="categoryList" :props="{
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      }" @change="handleCategoryChange" style="margin-left: 100px;"></el-cascader>
      <!-- 默认选中第一个 -->
      <el-tabs :tab-position="tabPosition = 'top'" style="height: 70px;" active-name="dynamic" @tab-click="handleTabChange">
        <el-tab-pane label="动态参数" name="dynamic">动态参数</el-tab-pane>
        <el-tab-pane label="静态参数" name="static">静态参数</el-tab-pane>
      </el-tabs>
      <el-button type="primary" :disabled="!selectedCategoryId" style="margin-bottom: 20px;"
        @click="addParamDialogVisible = true">添加参数</el-button>

      <el-table style="width: 100%" border :data="productParams.attrs">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-tag :key="tag.id + '-' + index" v-for="tag, index in scope.row.attr_vals" closable
              :disable-transitions="false" @close="removeTag(tag)">
              {{ tag.val }}
            </el-tag>
            <el-input class="input-new-tag" v-show="scope.row.attr_vals.isInputVisible" v-model="scope.row.attr_vals.newInput"
              ref="newTagInput" size="small" @keyup.enter.native="$event.target.blur()"
              @blur="confirmAddTag(scope.row)" style="width: 100px;">
            </el-input>
            <el-button v-show="!scope.row.attr_vals.isInputVisible" class="button-new-tag" size="small"
              @click="showTagInput(scope.row)">+ New Tag</el-button>
          </template>
        </el-table-column>
        <el-table-column label="参数类型"> </el-table-column>
        <el-table-column label="参数名称" prop="attr_name">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" @click="editParam(scope.row.attr_id)">编辑</el-button>
            <el-button type="danger" @click="deleteParam(scope.row.attr_id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog title="修改参数" :visible.sync="editParamDialogVisible" width="30%" center style="line-height: 0;">
      <el-input v-model="productParams.paramName" placeholder="请输入参数名称"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateParam">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="添加参数" :visible.sync="addParamDialogVisible" width="30%" center style="line-height: 0;">
      <el-input v-model="productParams.newParamName" placeholder="请输入参数名称"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParam">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import axios from 'axios';
import http from '@/mixins/http';

// 统一错误处理函数
const handleApiError = (error, errorMessage) => {
  console.error(errorMessage, error);
  return null;
};

export default {
  mixins: [http()],
  data() {
    return {
      categoryList: [],
      apiBaseUrl: 'http://43.138.15.137:7000/api/private/v1',
      authToken: localStorage.getItem('token'),
      selectedCategoryPath: [],
      selectedCategoryId: 0,
      dynamicTags: ['标签一', '标签二', '标签三'],
      inputVisible: true,
      inputValue: '',
      editParamDialogVisible: false,
      addParamDialogVisible: false,
      // 商品参数
      productParams: {
        attrs: [],
        newVal: '',
        paramType: 'many',
        paramName: '',
        paramId: 0,
        newParamName: ''
      }
    };
  },
  created() {
    this.fetchCategoryList();
  },
  methods: {
    // 删除标签
    removeTag(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },
    // 显示标签输入框
    showTagInput(paramItem) {
      this.$set(paramItem.attr_vals, 'isInputVisible', true);
      this.$nextTick(() => {
        this.$refs.newTagInput.$refs.input.focus();
      });
    },
    // 确认添加标签
    async confirmAddTag(paramRow) {
      try {
        paramRow.attr_vals.push({
          val: paramRow.attr_vals.newInput,
          isInputVisible: false,
          newInput: ''
        });
        paramRow.attr_vals.isInputVisible = false;
        paramRow.attr_vals.newInput = '';

        const requestData = {
          attr_name: paramRow.attr_name,
          attr_sel: paramRow.attr_sel,
          attr_vals: paramRow.attr_vals.map(item => item.val).join(',')
        };

        await this.$httpPut(`/categories/${this.selectedCategoryId}/attributes/${paramRow.attr_id}`, requestData);
        this.fetchProductAttributes(this.selectedCategoryId);
        this.$message({
          message: '添加成功',
          type: 'success'
        });
      } catch (error) {
        handleApiError(error, '添加标签请求失败:');
        this.$message.error('添加失败');
      }
    },
    // 更新参数
    async updateParam() {
      try {
        const requestData = {
          attr_name: this.productParams.paramName,
          attr_sel: this.productParams.paramType
        };

        await this.$httpPut(`/categories/${this.selectedCategoryId}/attributes/${this.productParams.paramId}`, requestData);
        this.fetchProductAttributes(this.selectedCategoryId);
        this.$message({
          type: 'success',
          message: '修改成功'
        });
        this.editParamDialogVisible = false;
        this.productParams.paramName = '';
      } catch (error) {
        handleApiError(error, '更新参数请求失败:');
        this.$message.error('修改失败');
      }
    },
    // 获取分类列表
    async fetchCategoryList() {
      try {
        const requestParams = {
          type: 3,
          pagesize: 100,
          pagenum: 1
        };
        const response = await this.$httpGet('/categories', requestParams);
        const { meta, data } = response.data;
        this.categoryList = data.result;
      } catch (error) {
        handleApiError(error, '获取分类列表请求失败:');
        this.$message.error('数据加载失败');
      }
    },
    // 获取商品属性
    fetchProductAttributes(categoryId, paramType = 'many', targetArray = this.productParams.attrs) {
      axios.get(`${this.apiBaseUrl}/categories/${categoryId}/attributes`, {
        params: {
          sel: paramType
        },
        headers: {
          'Authorization': this.authToken
        }
      })
      .then(response => {
        const { data: { data: attributesData, meta } } = response;
        targetArray.splice(0, targetArray.length, ...attributesData);
        attributesData.forEach(item => {
          item.attr_vals = item.attr_vals.split(',');
          item.attr_vals = item.attr_vals.map(val => ({
            val,
            isInputVisible: true,
            newInput: ''
          }));
        });
        console.log(targetArray);
      })
      .catch(error => {
        handleApiError(error, '获取商品属性请求失败:');
      });
    },
    // 处理分类选择变化
    handleCategoryChange() {
      this.selectedCategoryId = this.selectedCategoryPath[this.selectedCategoryPath.length - 1];
      this.fetchProductAttributes(this.selectedCategoryId);
    },
    // 处理标签点击
    handleTabChange(tab) {
      if (tab.name === 'dynamic') {
        this.productParams.paramType = 'many';
        this.fetchProductAttributes(this.selectedCategoryId);
      } else if (tab.name === 'static') {
        this.productParams.paramType = 'only';
        this.fetchProductAttributes(this.selectedCategoryId, 'only');
      }
    },
    // 删除参数
    deleteParam(paramId) {
      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await this.$httpDelete(`/categories/${this.selectedCategoryId}/attributes/${paramId}`);
          this.fetchProductAttributes(this.selectedCategoryId);
        } catch (error) {
          handleApiError(error, '删除参数请求失败:');
          this.$message.error('删除失败');
        }
      });
    },
    // 编辑参数
    editParam(paramId) {
      this.productParams.paramId = paramId;
      this.editParamDialogVisible = true;
    },
    // 添加参数
    async addParam() {
      try {
        const response = await this.$httpPost(`/categories/${this.selectedCategoryId}/attributes`, {
          attr_name: this.productParams.newParamName,
          attr_sel: this.productParams.paramType
        });
        this.fetchProductAttributes(this.selectedCategoryId);
        this.productParams.newParamName = '';
        this.$message({
          message: '添加成功',
          type: 'success'
        });
        this.addParamDialogVisible = false;
      } catch (error) {
        handleApiError(error, '添加参数请求失败:');
        this.$message.error('添加失败');
      }
    }
  }
};
</script>
<style>
.title p {
  color: rgb(239, 183, 86);
  margin-left: 20px;
}

.title {
  width: 100%;
  background-color: rgba(239, 183, 86, 0.24);
  height: 40px;
  display: flex;
  justify-content: left;
  align-items: center;
  border-radius: 5px;
  margin-bottom: 20px;
  color: rgb(239, 183, 86);
}

.el-tag+.el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
